package com.study.springsecurity.security.voters;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 所有人可访问决策器
 *
 * @Author YL
 * @Create 2024/4/17 16:16
 * @Version 1.0
 */
public class PermitAllVoter implements AccessDecisionVoter<FilterInvocation> {

    /**
     * 判断当前Voter是否支持对ConfigAttribute访问规则进行决策
     *
     * @param attribute
     * @return
     */
    @Override
    public boolean supports(ConfigAttribute attribute) {
        return attribute instanceof PermitAllConfigAttribute;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

    /**
     * 根据 authentication 和 attributes 决策当前用户是否有权限访问 object
     * 返回 ACCESS_GRANTED 表示有权限，返回 ACCESS_DENIED 表示无权限，返回 ACCESS_ABSTAIN 表示放行
     *
     * @param authentication   包含用户认证信息
     * @param filterInvocation 包含FilterChain、HttpServletRequest、HttpServletResponse
     * @param attributes
     * @return
     */
    @Override
    public int vote(Authentication authentication, FilterInvocation filterInvocation, Collection<ConfigAttribute> attributes) {
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        for (ConfigAttribute attribute : attributes) {
            if (this.supports(attribute)) {
                result = ACCESS_DENIED;
                if (attribute.getAttribute().equals(PermitAllConfigAttribute.permitAll)) {
                    return ACCESS_GRANTED;
                }
            }
        }
        return result;
    }

    /**
     * PermitAll 允许所有人访问的规则
     *
     * @Author YL
     * @Create 2024/4/17 18:00
     * @Version 1.0
     */
    public static class PermitAllConfigAttribute extends SecurityConfig {
        public static final String permitAll = "permitAll";
        private PermitAllConfigAttribute(){
            super(permitAll);
        }

        public static List<ConfigAttribute> createSingletonList() {
            return Collections.singletonList(new PermitAllConfigAttribute());
        }
    }
}
